/**
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.sebastianqu.common.widget;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.res.TypedArray;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

import com.example.android.Demo.R;

/**
 * DateButton
 *
 * @author qu sheng
 */
public class DateButton extends Button {

// ------------------- Private Fields
    private static String TAG = DateButton.class.getSimpleName();
    private static String STRING_FORMAT = "yyyyMMdd";
    private static String DEFAULT_FORMAT = "yyyy/MM/dd";
    private Date mDate;
    private String format;

// -------------- Public
    /**
     * Public Constructors
     *
     * @param context
     */
    public DateButton(Context context) {
        super(context);
        Log.d(TAG, "DateButton(Context context)");
        initMembers();
    }

    /**
     * Public Constructors
     *
     * @param context
     * @param attrs
     */
    public DateButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        Log.d(TAG, "DateButton(Context context, AttributeSet attrs)");
        initMembers();
        TypedArray ta = context.obtainStyledAttributes(attrs,
                R.styleable.DateButton);

        String format = ta.getString(R.styleable.DateButton_dateFormat);
        String value = ta.getString(R.styleable.DateButton_dateValue);
        setFormat(format);
        setValue(value);
        ta.recycle();
    }

    /**
     * Public Constructors
     *
     * @param context
     * @param attrs
     * @param defStyle
     */
    public DateButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        Log.d(TAG, "DateButton(Context context, AttributeSet attrs, int defStyle)");
        initMembers();
    }

    /**
     *
     * @return
     */
    public String getDataString() {
        Log.d(TAG, "getDataString");
        SimpleDateFormat df = new SimpleDateFormat(STRING_FORMAT);
        if (null == this.mDate) {
            return df.format(new Date());
        }
        return df.format(this.mDate);
    }

    /**
     * 返回日期
     *
     * @return 日期
     */
    public Date getValue() {
        Log.d(TAG, "getValue");
        return this.mDate;
    }

    /**
     * the date to set
     *
     * @param date
     */
    public void setValue(String date) {
        Log.d(TAG, "setValue");
        try {
        if (null != date && !"".equals(date))
            this.mDate = new Date(date);
        } catch (IllegalArgumentException ex) {
            if (isInEditMode()) {
                this.mDate = new Date();
            } else {
                throw ex;
            }
        }
        this.setText(null, null);
    }

    /**
     * 返回显示用的日期字符串
     *
     * @return 显示用的日期字符串
     */
    public String getViewString() {
        Log.d(TAG, "getViewString");
        SimpleDateFormat df;
        if (null == this.format || "".equals(this.format)) {
            if (!isInEditMode()) {
                df = (SimpleDateFormat) DateFormat.getDateFormat(this.getContext());
            } else {
                df = new SimpleDateFormat(DEFAULT_FORMAT);
            }
        } else {
            df = new SimpleDateFormat(this.format);
        }
        if (this.isInEditMode() && null == this.mDate) {
            return df.format(new Date());
        }
        if (this.mDate == null)
            return df.format(new Date());
        return df.format(this.mDate);
    }

    /**
     * @see TextView
     */
    @Override
    public void setText(CharSequence text, BufferType type) {
        Log.d(TAG, "setText(" + text + ")");
        super.setText(getViewString(), type);
    }

    /**
     * @see TextView
     */
    @Override
    public String getText() {
        Log.d(TAG, "getText");
        return getDataString();
    }

    /**
     * @return the formate
     */
    public String getFormat() {
        Log.d(TAG, "getFormat");
        return format;
    }

    /**
     * @param formate
     *            the formate to set
     */
    public void setFormat(String format) {
        Log.d(TAG, "setFormat");
        if (null != format || !"".equals(format)) this.format = format;
    }

// ----------------------- Private
    private void initMembers() {
        Log.d(TAG, "initMembers");
        this.mDate = new Date();
        this.format = ((SimpleDateFormat) DateFormat.getLongDateFormat(this
                .getContext())).toPattern();
        if (!isInEditMode()) this.setOnClickListener(new DateButtonOnClickListener());
    }

// ----------------------- Protected
    /**
     *
     */
    protected class DateButtonOnClickListener implements OnClickListener {
        /**
         *
         */
        @Override
        public void onClick(View v) {
            if (!isInEditMode()) {
                DatePickerDialog dialog = new DatePickerDialog(v.getContext(),
                        new OnDateSetListener(), mDate.getYear() + 1900, mDate.getMonth(),
                        mDate.getDate());
                dialog.show();
            }
        }
    }

    protected class OnDateSetListener implements DatePickerDialog.OnDateSetListener {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            mDate = new Date(year - 1900, monthOfYear, dayOfMonth);
            setText(getViewString(), null);
        }

    }
}
